package cn.wd.service.impl;

import cn.wd.domain.BulletMsg;
import cn.wd.domain.ReportTable;
import cn.wd.domain.User;
import cn.wd.mapper.BulletMsgMapper;
import cn.wd.mapper.ReportTableMapper;
import cn.wd.mapper.UserMapper;
import cn.wd.page.PageResult;
import cn.wd.qo.QueryObject;
import cn.wd.service.IBulletMsgService;
import cn.wd.utils.TokenManager;
import cn.wd.vo.LoginInfo;
import cn.wd.vo.ReportBulletMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BulletMsgServiceImpl implements IBulletMsgService {

    private final BulletMsgMapper mapper;

    private final UserMapper userMapper;

    private final ReportTableMapper reportTableMapper;

    public BulletMsgServiceImpl(BulletMsgMapper mapper, ReportTableMapper reportTableMapper, UserMapper userMapper) {
        this.mapper = mapper;
        this.reportTableMapper = reportTableMapper;
        this.userMapper = userMapper;
    }

    @Override
    public void save(BulletMsg obj) {
        mapper.insert(obj);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateById(BulletMsg obj) {
        mapper.updateByPrimaryKey(obj);
    }

    @Override
    public BulletMsg selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BulletMsg> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public PageResult<BulletMsg> query(QueryObject qo) {
        Long total = mapper.selectForCount(qo);
        if (total == 0) {
            return PageResult.empty(qo.getCurrentPage(), qo.getPageSize());
        }
        List<BulletMsg> bulletMsgList = mapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), total, bulletMsgList);
    }

    @Override
    public void reportBulletMsg(ReportBulletMsg reportBulletMsg) {
        LoginInfo info = TokenManager.get(reportBulletMsg.getToken());
        if (info != null) {
            ReportTable reportTable = new ReportTable();
            User userInfo = userMapper.selectByPrimaryKey(info.getId());
            User user = new User();
            user.setId(userInfo.getId());
            user.setNickname(userInfo.getNickname());

            // TODO 弹幕相关的信息

            BulletMsg bulletMsgInfo = mapper.selectByPrimaryKey(reportBulletMsg.getCid());
            BulletMsg bulletMsg = new BulletMsg();
            bulletMsg.setId(bulletMsgInfo.getId());
            bulletMsg.setContent(bulletMsgInfo.getContent());

            // TODO 执行举报弹幕添加功能
            reportTable.setUser(user);
            reportTable.setBullet(bulletMsg);
            reportTable.setReportContent(reportBulletMsg.getReportInfo());
            reportTable.setReportDesc(reportBulletMsg.getReportDes());
            reportTableMapper.insert(reportTable);
        }
    }
}
